<template>
  <div class="permissions-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>权限管理</span>
          <el-button type="primary" @click="openAddDialog" size="small" :disabled="!canPermOperate()">新增权限</el-button>
        </div>
      </template>
      <el-table :data="permissions" style="width: 100%" v-loading="loading">
        <el-table-column label="权限名称" min-width="180">
          <template #default="{ row }">
            <div>
              <div>{{ row.permissionNameChinese }}</div>
              <div style="font-size: 12px; color: #999;">{{ row.permissionName }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="260">
          <template #default="{ row }">
            <el-button size="small" @click="openEditDialog(row)" :disabled="!canPermOperate()">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)" :loading="deleteLoadingId === row.id" :disabled="!canPermOperate()">删除</el-button>
            <el-button size="small" type="info" @click="openAssignRoleDialog(row)" :disabled="!canPermOperate()">分配角色</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog :title="editMode ? '编辑权限' : '新增权限'" v-model="dialogVisible" width="400px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="权限名称" prop="permissionName">
          <el-input v-model="form.permissionName" maxlength="32" show-word-limit />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>

    <el-dialog title="分配角色" v-model="assignRoleDialogVisible" width="500px">
      <el-table :data="allRoles" style="width: 100%" v-loading="rolesLoading">
        <el-table-column prop="roleName" label="角色名称" min-width="180" />
        <el-table-column label="已分配" width="100">
          <template #default="{ row }">
            <el-checkbox v-model="row.assigned" @change="val => handleAssignChange(val, row)"></el-checkbox>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="assignRoleDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import permissionAPI from '@/api/permission'
import roleAPI from '@/api/role'
import { getPermissionChineseName } from '@/utils/permissionMapping'
import { useUserStore } from '@/stores/user'

const permissions = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const editMode = ref(false)
const form = reactive({ permissionName: '', id: null })
const formRef = ref()
const submitLoading = ref(false)
const deleteLoadingId = ref(null)
const assignRoleDialogVisible = ref(false)
const allRoles = ref([])
const rolesLoading = ref(false)
const currentPermission = ref(null)

const rules = {
  permissionName: [
    { required: true, message: '请输入权限名称', trigger: 'blur' },
    { min: 2, max: 32, message: '长度2-32个字符', trigger: 'blur' }
  ]
}

async function fetchPermissions() {
  loading.value = true
  try {
    const response = await permissionAPI.getPermissions()
    console.log('权限API响应:', response) // 调试日志

    if (response.code === 200 && Array.isArray(response.value)) {
      const permissionsData = response.value
      console.log('权限数据:', permissionsData) // 调试日志

      permissions.value = permissionsData.map(item => ({
        id: item.ID || item.id,
        permissionName: item.PermissionName || item.permissionName,
        permissionNameChinese: getPermissionChineseName(item.PermissionName || item.permissionName),
        isActived: item.IsActived ?? item.isActived ?? true,
        createdAt: item.CreatedAt || item.createdAt ? new Date(item.CreatedAt || item.createdAt).toLocaleString() : ''
      }))
    } else {
      console.error('权限响应数据格式错误:', response)
      ElMessage.error(response.msg || '获取权限列表失败')
      permissions.value = []
    }
  } catch (error) {
    console.error('获取权限列表失败:', error)
    ElMessage.error('获取权限列表失败')
    permissions.value = []
  } finally {
    loading.value = false
  }
}

const userStore = useUserStore()
const currentRole = computed(() => {
  const info = userStore.userInfo || {}
  if (Array.isArray(info.roles) && info.roles.length > 0) return info.roles[0]
  return info.role || 'User'
})
const canPermOperate = () => currentRole.value === 'Boss' || currentRole.value === 'Manager'

function openAddDialog() {
  if (!canPermOperate()) {
    ElMessage.error('权限不足')
    return
  }
  editMode.value = false
  form.permissionName = ''
  form.id = null
  dialogVisible.value = true
}

function openEditDialog(row) {
  if (!canPermOperate()) {
    ElMessage.error('权限不足')
    return
  }
  editMode.value = true
  form.permissionName = row.permissionName
  form.id = row.id
  dialogVisible.value = true
}

function submitForm() {
  formRef.value.validate(async valid => {
    if (!valid) return
    submitLoading.value = true
    try {
      if (editMode.value) {
        // 编辑
        await permissionAPI.updatePermission(form.id, { permissionName: form.permissionName })
        ElMessage.success('修改成功')
        await userStore.refreshUserInfo()
      } else {
        // 新增
        await permissionAPI.addPermission({ permissionName: form.permissionName })
        ElMessage.success('新增成功')
      }
      dialogVisible.value = false
      fetchPermissions()
    } catch (error) {
      console.error('操作失败:', error)
      ElMessage.error('操作失败')
    } finally {
      submitLoading.value = false
    }
  })
}

function handleDelete(row) {
  if (!canPermOperate()) {
    ElMessage.error('权限不足')
    return
  }
  ElMessageBox.confirm('确定要删除该权限吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      deleteLoadingId.value = row.id
      try {
        await permissionAPI.deletePermission(row.id)
        ElMessage.success('删除成功')
        await userStore.refreshUserInfo()
        fetchPermissions()
      } catch (error) {
        ElMessage.error('删除失败')
      } finally {
        deleteLoadingId.value = null
      }
    })
}

async function openAssignRoleDialog(permission) {
  if (!canPermOperate()) {
    ElMessage.error('权限不足')
    return
  }
  assignRoleDialogVisible.value = true
  currentPermission.value = permission
  rolesLoading.value = true
  try {
    // 获取所有角色
    const response = await roleAPI.getRoles()
    let roles = response.value || []

    // 获取已分配该权限的角色
    const detailRes = await permissionAPI.getPermissionById(permission.id)
    const assignedRoles = (detailRes.value && detailRes.value.roles) ? detailRes.value.roles : []
    const assignedRoleIds = assignedRoles.map(r => r.id || r.ID)

    // 标记哪些角色已分配
    roles = roles.map(role => ({
      ...role,
      assigned: assignedRoleIds.includes(role.id || role.ID)
    }))
    allRoles.value = roles
  } catch (error) {
    ElMessage.error('获取角色失败')
  } finally {
    rolesLoading.value = false
  }
}

async function handleAssignChange(checked, role) {
  if (!currentPermission.value) return
  if (checked) {
    // 分配权限
    try {
      await roleAPI.assignPermissions({
        roleId: role.id || role.ID,
        permissionId: currentPermission.value.id
      })
      ElMessage.success('分配成功')
    } catch (error) {
      ElMessage.error('分配失败')
      role.assigned = false
    }
  } else {
    // 只移除该角色的当前权限
    try {
      await roleAPI.removeRolePermission({
        roleId: role.id || role.ID,
        permissionId: currentPermission.value.id
      })
      ElMessage.success('移除成功')
    } catch (error) {
      ElMessage.error('移除失败')
      role.assigned = true
    }
  }
}

onMounted(fetchPermissions)
</script>

<style scoped>
.permissions-container {
  padding: 24px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
